import resetForm from './resetForm';
import serviceCommand from './serviceCommand';
import getCommand from './getCommand';
import loading from './loading';
import formValidator from './formValidator';
import handleDownload from './handleDownload';

/**
 * 表单加载数据和保存数据通用流程
 */
export default {
  mixins: [
    serviceCommand,
    resetForm,
    handleDownload,
    formValidator,
    getCommand,
    loading,
  ],

  methods: {
    bindSave(api, action, sendingData,
      {
        callback = this.$_defaultSendingCommandFunc,
        successMessage = '保存成功',
        beforeSend = data => data,
        afterSuccess = _.noop,
      } = {}) {
      this.bindCommand({
        type: 'save',
        api,
        sendingData,
        callback,
        beforeAction: beforeSend,
        action,
      },
      {
        successMessage,
        afterSuccess,
      });
    },

    doSave({ action, form }) {
      if (form) {
        this.doAction({ type: 'save', action, canExec: this.$_validateForms(form) });
      } else {
        this.doAction({ type: 'save', action });
      }
    },

    $_defaultSendingCommandFunc([result, data],
      {
        successMessage = '',
        errorMessage = `保存失败.${data && data.message}`,
        afterSuccess,
      }) {
      if (result) {
        this.$notify({
          // title: errorMessage,
          // message: errorMessage,
          title: successMessage,
          type: 'success',
          // type: 'error',
          duration: 2000,
        });

        if (afterSuccess) {
          afterSuccess([result, data]);
        }
      } else {
        this.$notify({
          title: errorMessage,
          // message: errorMessage,
          type: 'error',
          duration: 2000,
        });
      }
    },
  },
};
